import { post, put } from '../../services/request.js'

const state = {
  userInfo: null,
  isLoggedIn: false,
  accessToken: '',
  refreshToken: '',
  isLoading: false,
  // 是否需要提示用户授权头像和昵称（用于在页面上显示授权按钮）
  needProfilePrompt: false
}

const mutations = {
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    state.isLoggedIn = !!userInfo
    if (userInfo) {
      uni.setStorageSync('userInfo', userInfo)
    }
  },
  SET_TOKENS(state, { accessToken, refreshToken }) {
    state.accessToken = accessToken
    state.refreshToken = refreshToken
    if (accessToken) {
      uni.setStorageSync('accessToken', accessToken)
    }
    if (refreshToken) {
      uni.setStorageSync('refreshToken', refreshToken)
    }
  },
  SET_ACCESS_TOKEN(state, accessToken) {
    state.accessToken = accessToken
    if (accessToken) {
      uni.setStorageSync('accessToken', accessToken)
    }
  },
  SET_LOADING(state, loading) {
    state.isLoading = loading
  },
  CLEAR_AUTH(state) {
    state.userInfo = null
    state.isLoggedIn = false
    state.accessToken = ''
    state.refreshToken = ''
    state.isLoading = false
    state.needProfilePrompt = false
    uni.removeStorageSync('accessToken')
    uni.removeStorageSync('refreshToken')
    uni.removeStorageSync('userInfo')
  },
  SET_NEED_PROFILE_PROMPT(state, need) {
    state.needProfilePrompt = !!need
  }
}

const actions = {
  // 冷启动恢复登录状态
  async restoreLoginStatus({ commit }) {
    const accessToken = uni.getStorageSync('accessToken')
    const refreshToken = uni.getStorageSync('refreshToken')
    const userInfo = uni.getStorageSync('userInfo')
    
    if (accessToken && refreshToken && userInfo) {
      commit('SET_TOKENS', { accessToken, refreshToken })
      commit('SET_USER_INFO', userInfo)
      
      // 验证 token 有效性
      try {
        await this.dispatch('auth/validateToken')
      } catch (error) {
        console.warn('token 验证失败，尝试刷新:', error)
        try {
          await this.dispatch('auth/refreshToken')
        } catch (refreshError) {
          console.warn('刷新token失败，清理登录状态:', refreshError)
          commit('CLEAR_AUTH')
        }
      }
    }
  },

  // 验证 token 有效性
  async validateToken({ commit, state }) {
    if (!state.accessToken) {
      throw new Error('No access token found')
    }

    try {
      const response = await post('/api/wxapp/auth/profile', {}, { 
        showLoading: false,
        preventDuplicate: false 
      })
      
      if (response && response.success) {
        commit('SET_USER_INFO', response.user)
        // 如果资料不完整，触发提示标记
        const isDefaultAvatar = !response.user.avatar || String(response.user.avatar).includes('default-avatar.png')
        const isPlaceholderNickname = !response.user.nickname || 
          String(response.user.nickname) === '微信用户' ||
          /^微信用户\w{4}$/.test(String(response.user.nickname)) || 
          String(response.user.nickname) === '测试用户' ||
          String(response.user.nickname).startsWith('用户')
        commit('SET_NEED_PROFILE_PROMPT', isDefaultAvatar || isPlaceholderNickname)
        return response.user
      } else {
        throw new Error('Token validation failed')
      }
    } catch (error) {
      console.error('Token 验证失败:', error)
      throw error
    }
  },

  // 刷新token
  async refreshToken({ commit, state }) {
    if (!state.refreshToken) {
      throw new Error('No refresh token found')
    }

    try {
      const response = await post('/api/wxapp/auth/refresh', {
        refreshToken: state.refreshToken
      }, { 
        showLoading: false,
        preventDuplicate: false 
      })
      
      if (response && response.success) {
        commit('SET_TOKENS', {
          accessToken: response.accessToken,
          refreshToken: response.refreshToken
        })
        console.log('[auth] Token刷新成功')
        return response
      } else {
        throw new Error(response.message || '刷新token失败')
      }
    } catch (error) {
      console.error('[auth] Token刷新失败:', error)
      commit('CLEAR_AUTH')
      throw error
    }
  },

  // 检查登录状态（兼容旧方法名）
  checkLoginStatus({ dispatch }) {
    return dispatch('restoreLoginStatus')
  },

  // wxapp 手机号注册
  async register({ commit }, { phone, password, nickname }) {
    commit('SET_LOADING', true)
    
    try {
      const response = await post('/api/wxapp/auth/register', {
        phone,
        password,
        nickname
      }, { showLoading: true })

      if (response && response.success) {
        const { user, tokens } = response
        
        commit('SET_TOKENS', tokens)
        commit('SET_USER_INFO', user)
        
        console.log('[auth] 注册成功:', user.phone)
        return { success: true, user }
      } else {
        throw new Error(response.message || '注册失败')
      }
    } catch (error) {
      console.error('注册失败:', error)
      return { success: false, error: error.message }
    } finally {
      commit('SET_LOADING', false)
    }
  },

  // wxapp 手机号登录
  async phoneLogin({ commit }, { phone, password }) {
    commit('SET_LOADING', true)
    
    try {
      const response = await post('/api/wxapp/auth/login', {
        phone,
        password
      }, { showLoading: true })

      if (response && response.success) {
        const { user, tokens } = response
        
        commit('SET_TOKENS', tokens)
        commit('SET_USER_INFO', user)
        
        // 登录成功后检查是否缺少头像昵称
        console.log('[auth] 准备检查用户头像昵称...')
        dispatch('autoFetchProfile').catch(err => {
          console.error('[auth] autoFetchProfile 调用失败:', err)
        })
        
        console.log('[auth] 登录成功:', user.phone)
        return { success: true, user }
      } else {
        throw new Error(response.message || '登录失败')
      }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, error: error.message }
    } finally {
      commit('SET_LOADING', false)
    }
  },

  // 兼容旧版login方法（重定向到phoneLogin）
  async login({ dispatch }, { username, password }) {
    console.warn('login方法已更新，重定向到phoneLogin')
    // 假设username是手机号
    return await dispatch('phoneLogin', { phone: username, password })
  },

  // 微信登录（小程序）
  async wechatLogin({ commit, dispatch }, payload = {}) {
    commit('SET_LOADING', true)
    try {
      // 获取微信临时登录凭证 code
      const loginRes = await uni.login({ provider: 'weixin' })
      if (!loginRes.code) throw new Error('获取微信code失败')

      // 若组件侧已通过“用户手势”获取到头像昵称，则随payload传入
      // 否则为 null，登录完成后再提示用户补充授权
      let userInfo = (payload && payload.userInfo) ? payload.userInfo : null
      if (userInfo) {
        console.log('[微信登录] 收到来自UI的用户资料，将随登录一并提交')
      } else {
        console.log('[微信登录] 仅获取微信登录凭证，头像昵称将通过后续用户授权获取')
      }

      // 调用后端微信登录接口
      const response = await post('/api/wxapp/auth/wechat-login', {
        code: loginRes.code,
        userInfo
      }, { showLoading: true })

      if (response && response.success) {
        const { user, tokens } = response
        commit('SET_TOKENS', tokens)
        commit('SET_USER_INFO', user)
        
        // 检查是否需要补充获取头像昵称（只有在微信登录时未获取到才提示）
        const isDefaultAvatar = !user.avatar || String(user.avatar).includes('default-avatar.png')
        const isPlaceholderNickname = !user.nickname || 
          String(user.nickname) === '微信用户' ||
          /^微信用户\w{4}$/.test(String(user.nickname)) || 
          String(user.nickname) === '测试用户' ||
          String(user.nickname).startsWith('用户')
        
        // 微信登录完成后，检查是否需要获取头像昵称（由用户手势触发）
        if (isDefaultAvatar || isPlaceholderNickname) {
          console.log('[auth] 微信登录完成，检测到需要获取头像昵称，将提示用户授权')
          dispatch('autoFetchProfile').catch(err => {
            console.error('[auth] autoFetchProfile 调用失败:', err)
          })
        } else {
          console.log('[auth] 微信登录完成，用户资料完整')
        }
        
        return { success: true, user }
      } else {
        throw new Error(response.message || '微信登录失败')
      }
    } catch (error) {
      console.error('微信登录失败:', error)
      return { success: false, error: error.message }
    } finally {
      commit('SET_LOADING', false)
    }
  },

  // 兼容游客模式（暂时返回错误，需要引导用户注册）
  async guestAccess({ commit }) {
    commit('SET_LOADING', false)
    return { 
      success: false, 
      error: '请使用手机号注册登录' 
    }
  },

  // wxapp 登出
  async logout({ commit, state }) {
    try {
      // 调用wxapp登出接口
      await post('/api/wxapp/auth/logout', {
        refreshToken: state.refreshToken
      }, { 
        showLoading: false,
        preventDuplicate: false 
      })
      console.log('[auth] 登出成功')
    } catch (error) {
      console.warn('后端登出失败:', error)
    } finally {
      commit('CLEAR_AUTH')
      
      // 跳转到登录页
      uni.reLaunch({
        url: '/pages/login/index'
      })
    }
  },

  // 登录后自动获取并保存头像昵称
  async autoFetchProfile({ dispatch, state }) {
    try {
      const user = state.userInfo
      if (!user) return

      // 如果已有头像和昵称就不重复获取
      const isDefaultAvatar = !user.avatar || String(user.avatar).includes('default-avatar.png')
      const isPlaceholderNickname = !user.nickname || 
        String(user.nickname) === '微信用户' ||
        /^微信用户\w{4}$/.test(String(user.nickname)) || 
        String(user.nickname) === '测试用户' ||
        String(user.nickname).startsWith('用户')
      
      if (!isDefaultAvatar && !isPlaceholderNickname) {
        console.log('[auth] 用户资料已完整，无需授权')
        return
      }

      console.log('[auth] 检测到用户缺少头像或昵称，尝试获取...')
      // 标记需要在页面上展示授权按钮（更符合微信“用户手势触发”规范）
      dispatch('setNeedProfilePrompt', true)
      uni.showToast({
        title: '请授权头像昵称',
        icon: 'none'
      })
    } catch (error) {
      console.error('[auth] 自动获取头像昵称失败:', error)
    }
  },

  // 设置是否需要资料授权提示
  setNeedProfilePrompt({ commit }, need) {
    commit('SET_NEED_PROFILE_PROMPT', need)
  },

  // 由按钮点击触发：请求微信头像与昵称，并保存
  async requestUserProfile({ dispatch, commit, state }) {
    try {
      console.log('[授权按钮] 开始调用getUserProfile...')
      const current = state.userInfo || {}
      
      const userRes = await uni.getUserProfile({ 
        desc: '用于完善个人资料展示',
        lang: 'zh_CN'
      })
      
      console.log('[授权按钮] getUserProfile返回结果:', userRes)
      
      if (userRes && userRes.userInfo) {
        const nickname = (userRes.userInfo.nickName || userRes.userInfo.nickname || '').trim()
        const avatar = userRes.userInfo.avatarUrl || userRes.userInfo.avatar || current.avatar

        console.log('[授权按钮] 解析到的用户信息(直接保存):', { nickname, avatar })

        const result = await dispatch('saveProfile', { nickname, avatar })
        console.log('[授权按钮] saveProfile返回结果:', result)
        if (result && result.success) {
          commit('SET_NEED_PROFILE_PROMPT', false)
          uni.showToast({ title: '资料更新成功', icon: 'success' })
          return { success: true }
        }
        return { success: false, error: result?.error || '保存失败' }
      } else {
        console.log('[授权按钮] getUserProfile未返回用户信息')
        return { success: false, error: '未获取到用户信息' }
      }
    } catch (e) {
      console.log('[授权按钮] getUserProfile失败，完整错误信息:', e)
      console.log('[授权按钮] 错误类型:', typeof e)
      console.log('[授权按钮] 错误message:', e?.message || '无message')
      console.log('[授权按钮] 错误errCode:', e?.errCode || '无errCode')
      
      if (e?.errMsg && e.errMsg.includes('cancel')) {
        return { success: false, error: '用户取消授权' }
      }
      return { success: false, error: e?.message || '获取用户信息失败' }
    }
  },

  // 保存资料（昵称/头像）
  async saveProfile({ commit }, { nickname, avatar }) {
    try {
      console.log('[saveProfile] 开始保存资料，参数:', { nickname, avatar })
      
      const response = await put('/api/wxapp/auth/profile', { nickname, avatar }, {
        showLoading: false // 自动保存时不显示loading
      })
      
      console.log('[saveProfile] 后端返回结果:', response)
      
      if (response && response.success) {
        console.log('[saveProfile] 保存成功，更新本地用户信息')
        commit('SET_USER_INFO', response.user)
        return { success: true, user: response.user }
      }
      
      console.error('[saveProfile] 后端返回失败:', response?.message || '未知错误')
      throw new Error(response?.message || '保存失败')
    } catch (error) {
      console.error('[saveProfile] 保存资料异常:', error)
      return { success: false, error: error.message || error.toString() }
    }
  },

  // 更新用户信息
  updateUserInfo({ commit }, userInfo) {
    commit('SET_USER_INFO', userInfo)
  },

}

const getters = {
  isLoggedIn: state => state.isLoggedIn,
  userInfo: state => state.userInfo,
  needProfilePrompt: state => state.needProfilePrompt,
  // 兼容个人中心页面的认证状态显示
  isVerified: state => (state.userInfo && state.userInfo.isVerified) || false,
  accessToken: state => state.accessToken,
  refreshToken: state => state.refreshToken,
  // 兼容旧版token getter
  token: state => state.accessToken,
  isLoading: state => state.isLoading,
  userRole: state => state.userInfo?.roles?.[0] || 'wx_user'
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}